/*
 * Authentication token
 */
package com.spartancoder.accommodation.models;

import com.spartancoder.accommodation.beans.AdministratorBean;
import com.spartancoder.accommodation.beans.StudentBean;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;

/**
 *
 * @author andrei
 */
public class AuthToken {

	private static Logger log = Logger.getLogger(AuthToken.class.getName());

	public static final int GUEST_TOKEN = 0;
	public static final int ADMIN_TOKEN = 1;
	public static final int STUDENT_TOKEN = 2;

	private int tokenType = GUEST_TOKEN;
	private int tokenId = 0;
	
	private HttpSession session = null;
	private StudentBean studentBean = null;
	private AdministratorBean adminBean = null;

	public AuthToken(HttpSession session) {
		this.session = session;

		if (session.getAttribute("tokenType") != null) {
			tokenType = (Integer) session.getAttribute("tokenType");

			if (tokenType != GUEST_TOKEN &&
					tokenType != ADMIN_TOKEN &&
					tokenType != STUDENT_TOKEN) {

				log.severe("Invalid auth token type found on session");
				session.invalidate();
				throw new IllegalStateException("Invalid toke type");
			}
			tokenId = (Integer) session.getAttribute("tokenId");
		}
	}

	public void set(int tokenType, int tokenId) {
		if (tokenType != GUEST_TOKEN &&
			tokenType != ADMIN_TOKEN &&
			tokenType != STUDENT_TOKEN) {

			throw new IllegalArgumentException("Invalid token type");
		}
		this.tokenType = tokenType;
		this.tokenId = tokenId;

		session.setAttribute("tokenType", tokenType);
		session.setAttribute("tokenId", tokenId);
	}

	public void unset() {
		session.invalidate();
		this.tokenType = GUEST_TOKEN;
		this.tokenId = 0;
	}

	public void setStudent(int id) {
		set( STUDENT_TOKEN, id );
	}

	public void setAdministrator(int id) {
		set( ADMIN_TOKEN, id);
	}

	public StudentBean getStudent() {
		if (!isStudent()) {
			return null;
		}
		if (studentBean == null) {
			studentBean = Student.fetch(tokenId);
		}
		return studentBean;
	}

	public AdministratorBean getAdministrator() {
		if (!isAdmin()) {
			return null;
		}
		if (adminBean == null) {
			adminBean = Administrator.fetch(tokenId);
		}
		return adminBean;
	}

	public boolean isGuest() {
		return tokenType == GUEST_TOKEN;
	}

	public boolean isAdmin() {
		return tokenType == ADMIN_TOKEN;
	}

	public boolean isStudent() {
		return tokenType == STUDENT_TOKEN;
	}

	public int getType() {
		return tokenType;
	}

	public int getId() {
		return tokenId;
	}
}
